/*
 * # iohao.com . 渔民小镇
 * Copyright (C) 2021 - 2022 double joker （262610965@qq.com） . All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.iohao.game.simulation.client;

import com.iohao.game.simulation.client.config.ClientSimulationConfig;
import com.iohao.game.simulation.client.data.ActionDataManager;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import org.noear.solon.Solon;
import org.noear.solon.SolonApp;

import java.util.concurrent.TimeUnit;

/**
 * @author 渔民小镇
 * @date 2022-11-01
 */
@FieldDefaults(level = AccessLevel.PUBLIC)
public class ClientSimulation {

    public static String sessionId;

    /**
     * 模拟客户端的默认端口为 18080
     * <pre>
     *     一定要放在游戏服务器最后在地方启动
     * </pre>
     */
    public static void start() {
        start(ClientSimulationConfig.me().clientSimulationHttpPort);
    }

    public static void start(int webClientServerPort) {

        try {
            TimeUnit.MILLISECONDS.sleep(100);

            String[] args = new String[]{"server.port=" + webClientServerPort};

            internalStart(args);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static SolonApp internalStart(String[] args) {
        if (args == null) {
            args = new String[]{"server.port=" + ClientSimulationConfig.me().clientSimulationHttpPort};
        }

        System.getProperties().put("solon.mime.map ", "application/json");

        SolonApp start = Solon.start(ClientSimulation.class, args, app -> {
            //启用 WebSocket 服务
            app.enableWebSocket(true);

            //在后端把 / 变成 /index.html
            app.filter((ctx, chain) -> {
                if ("/".equals(ctx.pathNew())) {
                    ctx.pathNew("/index.html");
                }

                chain.doFilter(ctx);
            });

        });

        // 初始化模拟客户端端数据
        ActionDataManager.me().init();

        return start;
    }
}
